package util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.util.Log;
import dk.isten.andro.main.BaseApp;


/**
 *
 * @author Martin Juhl
 */

public class AarupbkXMLFeeds {
	public static ArrayList<Item> news = new ArrayList<Item>();
	public static String freshBifFeeds;
	public static String oldBifFeeds;
	public static final String PREFS_NAME = "MyPrefsFile";
	private int count = 0;
	private boolean setNewTimeStamp = true;
	private String feedURL= BaseApp.stamdata.json.optString("feedURL");
	

	public ArrayList<Item> getData(InputStream is, Context ctx) throws IOException
	{	

		try 
		{
			//from the Internet er fint

			try{
				URL data = new URL(feedURL);
				is = data.openStream();
				Log.d("aarupxmlfeed", "så har vi hentet nyheder fra nettet");
			} catch(Exception e1){
				Log.d("aarupxmlfeed", "vi bruger de gamle nyheder");
//					is = BaseApp.instans.getResources().openRawResource(R.raw.rssnews);
				System.out.println("we are using raw XML file");
				is.toString();
			}

			// Det kan være nødvendigt at hoppe over BOM mark - se http://android.forums.wordpress.org/topic/xml-pull-error?replies=2
			//is.read(); is.read(); is.read(); // - dette virker kun hvis der ALTID er en BOM
			// Hop over BOM - hvis den er der!
			is = new BufferedInputStream((is));  // bl.a. FileInputStream understøtter ikke mark, så brug BufferedInputStream
			is.mark(1); // vi har faktisk kun brug for at søge én byte tilbage
			if (is.read() == 0xef) 
			{
				is.read();
				is.read();
			} // Der var en BOM! Læs de sidste 2 byte
			else 
			{
				is.reset(); // Der var ingen BOM - hop tilbage til start
			}
			//Standard Java bruger xpp3-1.1.4.jar fra http://www.extreme.indiana.edu/xgws/xsoap/xpp/
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			XmlPullParser xpp = factory.newPullParser();

			//	XmlPullParser xpp = android.util.Xml.newPullParser();  // Android-kald til at oprette parser

			//xpp.setInput(is, "UTF-8"); // evt "ISO-8859-1"
			xpp.setInput(is, "UTF-8");

			int eventType = xpp.getEventType();
			//we take the data we need. title, description
			//link and pubdate
			Item item = null; 
			String s;
			String tag;
			while (eventType != XmlPullParser.END_DOCUMENT)
			{
				if (eventType == XmlPullParser.START_TAG)
				{
					item = new Item();

					tag = xpp.getName();

					try {						
						if ("item".equals(tag))
						{
							count++;
							//skip item
							xpp.nextTag();

							//TITLE
							xpp.getName();
							s = xpp.nextText();
							item.title = s;


							//LINK
							xpp.nextTag();
							s = xpp.nextText();
							item.link = s;


							//DESCRIPTION
							xpp.nextTag();

							while(!(eventType==XmlPullParser.START_TAG && xpp.getName().equals("category"))){
								eventType = xpp.next();
							}
							//							TODO Jeg skal have den til at tjekke for alle category's og ikke kun den første
							s = xpp.nextText();
							item.category = s;


							xpp.nextTag();
							//							while ikke startTAG og ikke description
							
							while(!(eventType==XmlPullParser.START_TAG && xpp.getName().equals("content:encoded"))){
								eventType = xpp.next();
							}
							s = xpp.nextText();
							item.content = s;

							//PUBDATE			
							xpp.nextTag();
							s = xpp.nextText();
							item.pubDate = s;
							//we need the first pubDate to compare dates later
							if (count == 1) freshBifFeeds = s;

							//add to arraylist
							news.add(item);
						}
					} catch (Exception e) {
						e.printStackTrace();
						System.out.println("An Error occured. The program crashed: " + e.toString());
						//show error messages
						//	tv.append("RSS feeds not avaiable. We are working on it.\n");
						System.out.println("RSS feeds not avaiable. We are working on it");
						news.clear();
						item = new Item();
						item.title = "RSS feeds not avaiable. We are working on it";
						news.add(item);
						setNewTimeStamp = false;
						break;

						//todo
						//contact app admin
						//implement a Intent that sends a e-mail to me
					}
				}
				eventType = xpp.next();
			}
			is.close();
		} 
		catch (Exception ex) 
		{
			ex.printStackTrace();
			//tv.append("FEJL:" + ex.toString());
			System.out.println("FEJL:" + ex.toString());
			news.clear();
			Item item = new Item();
			item.title = "RSS feeds er ikke tilgængelige. Vi arbejder på det";
			news.add(item);
			setNewTimeStamp = false;

		}

		//If no errors we want to set a new timestamp
		if (setNewTimeStamp == true)
			setTimeStamp(setNewTimeStamp, ctx);

		return news;
	}

	private void setTimeStamp(boolean bo, Context ctx)
	{
		System.out.println("BifXMLFeeds : setTimeStamp() : Boolean er: " + bo);

	}

	public ArrayList<Item> getNews() {
		return news;
	}
}